import axios from "axios";
import { Notification, MessageBox, Message, Loading } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import { tansParams, blobValidate } from "@/utils/ruoyi";
import cache from "@/plugins/cache";
import { saveAs } from "file-saver";
import { c_id, c_secret, rUri } from "@/settings";

export function uaaUrl() {
  return "";
}
export function ourl() {
  return process.env.VUE_APP_BASE_API;
}
//富文本编辑器开始
export function fileurl() {
  return fileUrl;
}

export function fileToken() {
  return filetoken;
}

export function UEditorurl() {
  return UEditorUrl;
}

export function AppUrl() {
  return "";
}

export function DataUrl() {
  return "";
}

var oUrl = process.env.VUE_APP_BASE_API;
var filetoken = "iAmRtlarUMenj2tKcPI5x4tYwWuUqLi8VM1qzzEz+cQ="; //开发-文件服务器token
var fileUrl = "";
var UEditorUrl = "http://124.71.128.227:11101/api-ueditor/v1/ueditor/exec"; //富文本url
//富文本编辑器结束
// var uaa = process.env.VUE_APP_ACCOUNT_URL; //认证地址
//rsa加密处理
/* 产引入encryptlong实现数据RSA加密 */
import Encrypt from "encryptlong"; // encryptlong是基于jsencrypt扩展的长文本分段加解密功能。
// 公钥key
const publicKey = process.env.VUE_APP_PUBLICkEY_VALUE;
/* 加密 */
const encrypt = function (data) {
  const PUBLIC_KEY = publicKey;
  var encryptor = new Encrypt();
  encryptor.setPublicKey(PUBLIC_KEY);
  // 如果是对象/数组的话，需要先JSON.stringify转换成字符串
  const result = encryptor.encryptLong(data);
  return result;
};

//加密规则
let limits = function () {
  var originUrl = window.location.origin
    .replace("http://", "")
    .replace("https://", "");

  var clientId = "59ccfe8c08a943488ffa945f7736d897";
  var clientType = "h5";
  var clientIdentification = originUrl;
  var time = "";
  time = JSON.stringify(Date.now());
  var info = "";
  info =
    "clientId=" +
    clientId +
    "&clientIdentification=" +
    clientIdentification +
    "&clientType=" +
    clientType +
    "&time=" +
    time;
  var valid = "";
  valid =
    clientId.charAt(clientId.length - 1) +
    clientIdentification.charAt(clientIdentification.length - 1) +
    clientType.charAt(clientType.length - 1) +
    time.charAt(time.length - 1);
  var sign = `ZH_AUTH:` + info + `&valid=` + valid;
  return { sign, clientId };
};

let downloadLoadingInstance;
// 是否显示重新登录
export let isRelogin = { show: false };
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 60000,
  withCredentials: true,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    // console.log("1");
    // // 断点
    // console.log(config, "config");
    // console.log(limits(), "limits");
    //添加请求头加密字段
    let signRsa = encrypt(limits().sign); //加密
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;

    //添加加密请求头
    // console.log(signRsa, "signRsa", limits().clientId, "clientId");
    if (signRsa && limits().clientId) {
      config.headers["sign"] = signRsa;
      config.headers["clientId"] = limits().clientId;
      if (getToken() && !isToken) {
        // 路径不为getProjectTypeTree时（请求其他服务的接口）添加 Authorization
        if (config.url.indexOf("getProjectTypeTree") === -1) {
          config.headers["Authorization"] = "Bearer " + getToken();
        }
      } else {
        // let ci = clinetId2 + ":" + clientSecret2;
        config.headers["Authorization"] =
          "Basic " +
          window.btoa(
            `${c_id}:${c_secret}`
            // "webapp:123456"
          );
      }
    } else {
      Message({ message: "未获取到项目权限,禁止使用!", type: "warning" });
      return config;
    }

    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (
      !isRepeatSubmit &&
      (config.method === "post" || config.method === "put")
    ) {
      const requestObj = {
        url: config.url,
        data:
          typeof config.data === "object"
            ? JSON.stringify(config.data)
            : config.data,
        time: new Date().getTime(),
      };
      const sessionObj = cache.session.getJSON("sessionObj");
      if (
        sessionObj === undefined ||
        sessionObj === null ||
        sessionObj === ""
      ) {
        cache.session.setJSON("sessionObj", requestObj);
      } else {
        const s_url = sessionObj.url; // 请求地址
        const s_data = sessionObj.data; // 请求数据
        const s_time = sessionObj.time; // 请求时间
        const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
        // if (
        //   s_data === requestObj.data &&
        //   requestObj.time - s_time < interval &&
        //   s_url === requestObj.url
        // ) {
        //   const message = "数据正在处理，请勿重复提交";
        //   console.warn(`[${s_url}]: ` + message);
        //   return Promise.reject(new Error(message));
        // } else {
        cache.session.setJSON("sessionObj", requestObj);
        // }
      }
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);
/*service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    } else {
      config.headers['Authorization'] = 'Basic ' + window.btoa('webapp:123456')
    }
    return config
  },
  error => {
    // console.log(error)
    // Promise.reject(error)
  }
)*/
// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode["default"];
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }

    if (code === 401) {
      // if (!isRelogin.show) {
      //   isRelogin.show = true;
      //   MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
      //     isRelogin.show = false;
      //     store.dispatch('LogOut').then(() => {
      //       location.href = '/index';
      //     })
      //   }).catch(() => {
      //     isRelogin.show = false;
      //   });
      // }
      // return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
      // 如果当前的页面地址是#/index，那么就不弹窗
      // console.log(
      //   window.location.href.indexOf("#/index") === -1,
      //   "不是登录页，进行弹窗"
      // );
      if (window.location.href.indexOf("#/index") === -1) {
        MessageBox.confirm(
          "登录状态已过期，您可以继续留在该页面，或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          // store.dispatch("LogOut").then(() => {
          //   location.reload(); // 为了重新实例化vue-router对象 避免bug
          // });
          // 去登录
          window.open(
            `${process.env.VUE_APP_LOGIN_URL}/api-uaa/v1/oauth/authorize?response_type=code&client_id=${c_id}&client_secret=${c_secret}&redirect_uri=${rUri}`,
            "_self"
          );
        });
      }
    } else if (code === 500) {
      Message({ message: msg, type: "error" });
      return Promise.reject(new Error(msg));
    } else if (code === 601) {
      Message({ message: msg, type: "warning" });
      return Promise.reject("error");
    } else if (code === 501) {
      return res.data;
    } else if (code !== 200) {
      // 如果请求地址是custom/login
      console.log(res.config.url, "res.config.url");
      if (res.config.url.indexOf("custom/login") !== -1) {
        return res.data;
      } else {
        Notification.error({ title: res.data.obj || msg });
        return Promise.reject(res.data.obj || msg);
      }

      // Notification.error({ title: res.data.obj || msg });
      // return Promise.reject(res.data.obj || msg);
    } else {
      return res.data;
    }
  },
  (error) => {
    let { message } = error;
    if (message == "Network Error") {
      message = "网络异常，请稍候再试";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({ message: message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return service
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      ...config,
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

export function download_get(url, filename, config) {
  downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return service
    .get(url, {
      responseType: "blob",
      ...config,
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

export default service;
